﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entity;
using IRepository;
using IService;

namespace Service
{
    public class SalesOrderService : ISalesOrderService
    {
        private readonly ISalesOrderRepository _salesOrder;
        public SalesOrderService(ISalesOrderRepository salesOrder) => _salesOrder = salesOrder;

        public Task<int> AddSalesOrderWithDetailsAsync(WMSOrderSalesOrder order, List<WMSOrderSalesOrderDetails> detailsList)
        {
            return _salesOrder.AddSalesOrderWithDetailsAsync(order, detailsList);
        }

        public Task<int> BatchAuditAsync(List<int> orderIds, string auditResult, string auditOpinion, string reviewer)
        {
            return _salesOrder.BatchAuditAsync(orderIds, auditResult, auditOpinion, reviewer);
        }

        public Task<int> BatchRevokeAsync(List<int> orderIds)
        {
            return _salesOrder.BatchRevokeAsync(orderIds);
        }

        public async Task<List<UserSelectDto>> GetAllPersonInChargeAsync()
        {
            var users = await _salesOrder.GetAllPersonInChargeAsync();
            return users.Select(u => new UserSelectDto
            {
                UserId = u.UserId,
                UserName = u.UserName
            }).ToList();
        }

        public async Task<PagedViewModel<ProductInformationEntity2>> GetAllProductInformationAsync(string product_code = null, string product_name = null, string unit = null, int currentPage = 1, int pageSize = 1)
        {
            // 1. 查询符合条件的全量数据
            List<ProductInformationEntity2> wMS_Basic_Customer2s = await _salesOrder.GetAllProductInformationAsync(product_code, product_name, unit);

            // 2. 内存分页（Skip + Take）
            List<ProductInformationEntity2> wMS_Basic_Customers = wMS_Basic_Customer2s
                .Skip((currentPage - 1) * pageSize)  // 跳过前N条
                .Take(pageSize)                       // 取当前页数据
                .ToList();

            // 3. 封装分页模型（包含“当前页数据”和“总条数”）
            PagedViewModel<ProductInformationEntity2> result = new PagedViewModel<ProductInformationEntity2>
            {
                items = wMS_Basic_Customers,  // 修正：与PagedViewModel的属性名保持一致（建议用items）
                total = wMS_Basic_Customer2s.Count    // 总数据条数
            };

            return result;
        }

        public async Task<PagedViewModel<WMSOrderSalesOrder2>> GetAllWMSOrderSalesOrder2Async(string sales_order_no = null, string document_status = null, string customer_name = null, DateTime? sales_date = null, int currentPage = 1, int pageSize = 2)
        {
            // 1. 查询符合条件的全量数据
            List<WMSOrderSalesOrder2> wMS_Basic_Customer2s = await _salesOrder.GetAllWMSOrderSalesOrder2Async(sales_order_no, document_status, customer_name, sales_date);

            // 2. 内存分页（Skip + Take）
            List<WMSOrderSalesOrder2> wMS_Basic_Customers = wMS_Basic_Customer2s
                .Skip((currentPage - 1) * pageSize)  // 跳过前N条
                .Take(pageSize)                       // 取当前页数据
                .ToList();

            // 3. 封装分页模型（包含“当前页数据”和“总条数”）
            PagedViewModel<WMSOrderSalesOrder2> result = new PagedViewModel<WMSOrderSalesOrder2>
            {
                items = wMS_Basic_Customers,  // 修正：与PagedViewModel的属性名保持一致（建议用items）
                total = wMS_Basic_Customer2s.Count    // 总数据条数
            };

            return result;
        }


        public Task<WMSBasicCustomer> GetCustomerDetailById(int customerId)
        {
          return _salesOrder.GetCustomerDetailById(customerId);
        }

        public Task<List<CustomerSelectDto>> GetCustomerSelectList()
        {
            return _salesOrder.GetCustomerSelectList();
        }

        public async Task<DeptByUserDto> GetDeptByUserIdAsync(int userId)
        {
            // 1. 校验参数
            if (userId <= 0)
                throw new ArgumentException("用户ID无效");

            // 2. 调用仓储层获取用户信息（包含所属部门ID）
            var user = await _salesOrder.GetUserByIdAsync(userId);
            if (user == null)
                return null; // 用户不存在或未启用

            // 3. 调用部门仓储获取部门名称（需实现IOrganizationRepository）
            var dept = await _salesOrder.GetOrganizationByIdAsync(user.OrganizationId);
            if (dept == null)
                return null; // 部门不存在

            // 4. 转换为部门DTO
            return new DeptByUserDto
            {
                OrganizationId = dept.organization_id,
                OrganizationName = dept.organization_name
            };
        }

        public Task<List<OrganizationTreeDto>> GetOrganizationTreeAsync()
        {
            return _salesOrder.GetOrganizationTreeAsync();
        }

        public Task<List<OrganizationTreeDto>> GetOrganizationTreeAsync2(string keyword)
        {
            return _salesOrder.GetOrganizationTreeAsync2(keyword);
        }

        public Task<WMSOrderSalesOrder2> GetSalesOrderDetailByNo(string saleOrderNo)
        {
           return _salesOrder.GetSalesOrderDetailByNo(saleOrderNo);
        }

        public async Task<List<UserSelectDto>> GetUsersByDeptIdAsync(int deptId)
        {
            // 1. 校验参数
            if (deptId <= 0)
                throw new ArgumentException("部门ID无效");

            // 2. 调用仓储层获取原始用户数据
            var userList = await _salesOrder.GetUsersByDeptIdAsync(deptId);

            // 3. 转换为前端需要的下拉框格式（只返回用户ID和名称）
            return userList.Select(u => new UserSelectDto
            {
                UserId = u.UserId,
                UserName = u.UserName
            }).ToList();
        }

        public Task<IEnumerable<dynamic>> GetUsersByOrgIdAsync(int orgId, string keyword = "")
        {
           return _salesOrder.GetUsersByOrgIdAsync(orgId, keyword);
        }

        public Task<List<int>> GetValidAuditOrderIdsAsync(List<int> orderIds)
        {
           return _salesOrder.GetValidAuditOrderIdsAsync(orderIds);
        }

        public Task<List<int>> GetValidRevokeOrderIdsAsync(List<int> orderIds)
        {
           return _salesOrder.GetValidRevokeOrderIdsAsync(orderIds);
        }

        public Task<int> LogicalDeleteBatch(List<string> saleOrderNos)
        {
           return _salesOrder.LogicalDeleteBatch(saleOrderNos);
        }

        public Task<int> LogicalDeleteSingle(string saleOrderNo)
        {
            return _salesOrder.LogicalDeleteSingle(saleOrderNo);
        }

        public Task<int> LogicalRevokeSingle(int saleOrderId)
        {
           return _salesOrder.LogicalRevokeSingle(saleOrderId);
        }
    }
}
